#!/usr/bin/env bash
set -euo pipefail

# 用法：
# ./publish_import.sh <远程主机> <远程用户> <远程密码>
# 示例：
# ./publish_import.sh 10.0.10.52 root "rhyfd2011"

REMOTE_HOST=${1:-}
REMOTE_USER=${2:-root}
REMOTE_PASS=${3:-}

if [ -z "$REMOTE_HOST" ] || [ -z "$REMOTE_PASS" ]; then
  echo "用法： $0 <远程主机> <远程用户> <远程密码>"
  exit 2
fi

IMAGE_NAME="qingyue/importer:latest"
TAR_FILE="importer_image.tar"
REMOTE_BASE_DIR="/data/importer"
LOCAL_CONFIG_DIR="apps/importer/config"
CONFIG_TAR="config_payload.tar.gz"

if ! command -v docker >/dev/null 2>&1; then
  echo "未检测到 docker 命令 — 请在本地安装 Docker 后再运行此脚本"
  exit 3
fi

if ! command -v sshpass >/dev/null 2>&1; then
  echo "未检测到 sshpass，正在尝试安装..."
  if command -v apt-get >/dev/null 2>&1; then
    apt-get update && apt-get install -y sshpass
  elif command -v yum >/dev/null 2>&1; then
    yum install -y epel-release && yum install -y sshpass
  elif command -v apk >/dev/null 2>&1; then
    apk add --no-cache sshpass
  else
    echo "请手动安装 sshpass 后重试"
    exit 4
  fi
fi

echo "正在构建 Docker 镜像 ${IMAGE_NAME}..."
docker build -f docker/Dockerfile.importer -t ${IMAGE_NAME} .

echo "正在保存镜像到 ${TAR_FILE}..."
docker save -o ${TAR_FILE} ${IMAGE_NAME}

echo "在远端创建目录并准备复制文件到 ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_BASE_DIR} ..."
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "mkdir -p ${REMOTE_BASE_DIR}/config ${REMOTE_BASE_DIR}/logs /mnt/novel /mnt/ebook"

echo "打包配置目录（排除 .go 文件）为 ${CONFIG_TAR}..."
tar --exclude='*.go' -czf ${CONFIG_TAR} -C ${LOCAL_CONFIG_DIR} .

echo "正在将配置包复制到远端..."
sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no ${CONFIG_TAR} ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_BASE_DIR}/${CONFIG_TAR}

echo "正在将镜像包复制到远端..."
sshpass -p "$REMOTE_PASS" scp -o StrictHostKeyChecking=no ${TAR_FILE} ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_BASE_DIR}/${TAR_FILE}

echo "在远端加载镜像并启动容器..."
sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} bash -s <<EOF
set -euo pipefail
cd ${REMOTE_BASE_DIR}
docker load -i ${TAR_FILE}
# 解压配置包到 config 目录（覆盖）
mkdir -p ${REMOTE_BASE_DIR}/config
tar -xzf ${CONFIG_TAR} -C ${REMOTE_BASE_DIR}/config

docker rm -f qy_importer || true
docker run -d \
  --name qy_importer \
  -e QY_CONFIG_DIR=/app/config \
  -e QY_LOG_DIR=/app/logs \
  -v ${REMOTE_BASE_DIR}/config:/app/config:ro \
  -v ${REMOTE_BASE_DIR}/logs:/app/logs \
  -v /mnt/novel:/mnt/novel \
  -v /mnt/ebook:/mnt/ebook \
  ${IMAGE_NAME}
EOF

echo "正在清理本地临时压缩包"
rm -f ${TAR_FILE} ${CONFIG_TAR}

echo "部署完成。容器名称：qy_importer，主机：${REMOTE_HOST}"


